package com.xishu.service;

import com.xishu.entity.order.Order;
import com.xishu.entity.order.OrderItem;
import com.xishu.entity.plat.DayReport;
import com.xishu.service.order.base.OrderService;
import com.xishu.util.DateUtil;
import com.xishu.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import java.util.List;
import java.util.Optional;

public class DayReportService implements Tools {
    private static Logger logger = LoggerFactory.getLogger(DayReportService.class);
    private static DayReportService instance = new DayReportService();

    private DayReportService() {
    }

    public static DayReportService getInstance() {
        return instance;
    }

    /**
     * 当天的统计信息
     *
     * @return
     */
    public DayReport todayDayReport() {
        DayReport dayReport = new DayReport();
        String currentDay = DateUtil.formatDayDate(System.currentTimeMillis());
        dayReport.setDay(currentDay);
        Optional<DayReport> dayReportOptional = CommonService.getInstance().searchOneOptional(dayReport);
        if (dayReportOptional.isPresent()) {
            //真实数据
            return dayReportOptional.get();
        }

        //假数据
        return new DayReport();
    }

    public void addSendKitchenNumber(Order orderInDb, List<Long> orderItemIdList) {
        if (isEmpty(orderItemIdList)) {
            logger.info("order item id list is empty");
            return;
        }

        //计算真实要发送到厨房里面的菜的数量
        List<OrderItem> orderItemList = OrderService.getInstance().filterOrderItemList(orderInDb, orderItemIdList);
        int sendKitchenNumber = getList(orderItemList).stream().mapToInt(p -> getInt(p.getCount())).sum();
        DayReportService.getInstance().addSendKitchenNumber(sendKitchenNumber);
    }


    /**
     * 添加发送到厨房的列表
     *
     * @param number
     */
    public void addSendKitchenNumber(long number) {
        String currentDay = DateUtil.formatDayDate(System.currentTimeMillis());
        CommonService commonService = CommonService.getInstance();
        DayReport reqDayReport = new DayReport();
        reqDayReport.setDay(currentDay);
        Optional<DayReport> dayReportOptional = commonService.searchOneOptional(reqDayReport);
        if (!dayReportOptional.isPresent()) {
            try {
                //没有的时间，新创建，创建成功后就返回
                create(currentDay, number);
                return;
            } catch (Exception e) {
                //创建失败过后，还是没有查询出来
                logger.error("e", e);
                return;
            }
        }

        //存在，则添加数量,乐观锁处理
        DayReport dayReport = dayReportOptional.get();
        dayReport.setSendKitchenNumber(commonService.getLong(dayReport.getSendKitchenNumber()) + number);
        try {
            commonService.save(dayReport);
        } catch (ObjectOptimisticLockingFailureException e) {
            addSendKitchenNumber(number);
        } catch (Exception e) {
            logger.error("e", e);
            return;
        }
    }

    public DayReport create(String currentDay, long number) throws Exception {
        DayReport dayReport = new DayReport();
        dayReport.setDay(currentDay);
        dayReport.setSendKitchenNumber(number);
        CommonService commonService = CommonService.getInstance();
        try {
            commonService.createObject(dayReport);
            return dayReport;
        } catch (Exception e) {
            DayReport reqDayReport = new DayReport();
            reqDayReport.setDay(currentDay);
            Optional<DayReport> dayReportOptional = commonService.searchOneOptional(reqDayReport);
            if (dayReportOptional.isPresent()) {
                //重新添加
                addSendKitchenNumber(number);
                return dayReportOptional.get();
            }

            throw e;
        }
    }
}
